package cn.heycm.blog.common.sms.service;

import cn.heycm.blog.common.sms.SmsProperties;
import cn.heycm.blog.common.sms.entity.SmsRequest;
import cn.heycm.blog.common.sms.entity.SmsResponse;
import cn.heycm.blog.common.utils.Jackson;
import com.apistd.uni.Uni;
import com.apistd.uni.UniException;
import com.apistd.uni.UniResponse;
import com.apistd.uni.sms.UniMessage;
import com.apistd.uni.sms.UniSMS;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author hey
 * @version 1.0
 * @since 2024/9/17 16:43
 */
@Slf4j
public class UniSmsServiceImpl implements SmsService {
    public UniSmsServiceImpl(SmsProperties smsProperties) {
        Uni.init(smsProperties.getAccessKey(), smsProperties.getAccessSecret());
    }

    @Override
    public SmsResponse send(SmsRequest smsRequest) {
        log.info("SMS Request: {}", Jackson.toJson(smsRequest));
        UniMessage message = UniSMS.buildMessage()
                .setTo(smsRequest.getTo())
                .setSignature(smsRequest.getSignature())
                .setTemplateId(smsRequest.getTemplateId())
                .setTemplateData(smsRequest.getTemplateData());
        try {
            UniResponse response = message.send();
            log.info("SMS Response: {}", Jackson.toJson(response));
            boolean success = "0".equals(response.code);
            if (success) {
                return SmsResponse.builder().code("0").message("success").build();
            }
            return SmsResponse.builder().code(response.code).message(response.message).build();
        } catch (UniException e) {
            log.error("SMS Send Error: {}", e.getMessage(), e);
            return SmsResponse.builder().code(e.code).message(e.message).build();
        } catch (Exception e) {
            log.error("SMS Send Error: {}", e.getMessage(), e);
        }
        return SmsResponse.builder().code("500").message("SMS Send Error").build();
    }
}
